package com.blog.web.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blog.common.core.web.page.TableDataInfo;
import com.blog.common.domain.entity.Category;
import com.blog.common.domain.vo.ArticleHomeVo;
import com.blog.common.domain.vo.CategoryVo;
import com.blog.common.mapper.dao.ArticleMapper;
import com.blog.common.mapper.dao.CategoryMapper;
import com.blog.web.service.CategoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 分类 服务实现类
 * </p>
 *
 * @author Valerie
 * @since 2023-02-18
 */
@Service
@RequiredArgsConstructor
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    private final CategoryMapper categoryMapper;


    private final ArticleMapper articleMapper;

    @Override
    public TableDataInfo<CategoryVo> listCategories(Serializable pageSize) {
        List<CategoryVo> categoryVoList = categoryMapper.listCategoryVo();
        Map<Long, List<CategoryVo>> subcategoryMap = categoryVoList.stream().collect(Collectors.groupingBy(CategoryVo::getPId));
        List<CategoryVo> resList = categoryVoList.stream().filter(f -> f.getPId() == 0).peek(p -> p.setSubcategoryList(subcategoryMap.get(p.getId()))).collect(Collectors.toList());
        if (pageSize != null){
            resList = resList.stream().limit(5).collect(Collectors.toList());
        }
        return new TableDataInfo<>(resList, categoryMapper.selectCount(null));
    }


    @Override
    public List<ArticleHomeVo> listArticlesByCategory(Serializable categoryId) {
        return articleMapper.listArticlesByCategory(categoryId);
    }
}
